package client;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
import java.rmi.*;
import java.util.Vector;
import javax.swing.JTextArea;
import java.util.ListIterator;
import java.io.*;
import java.net.*;

import ClientTests.RMIServer;


/*
 * Author: David Swords
 * Email: davidswordster@gmail.com
*/

public class Client
{
   	private String my_serverHost;
   	private int my_serverPort;
	private static final String SERVICE_TYPE = "music_service._udp.localhost.";
	private Vector<String[]> songList;

	public Client()
	{
		songList = new Vector<String[]>();
		
      		//my_serverHost = the_serverHost;
      		//my_serverPort = the_serverPort;
   	}
	
	public int getNumberOfSongs()
	{
		int count = songList.size();
		if(count==0)
		{
			System.out.println("It appears that no songs are available at the moment.");
			return 0;
		}
		else
			return count;
	}
	
	public String[] getTrack(int track)
	{
		return songList.get(track);
	}
	
	 // TODO: The list of songs available.
	
	@SuppressWarnings("deprecation")
	public void getListOfSongs()
	{
		String[] tags = {"<artist>","</artist>","<album>","</album>","<title>","</title>","<location>","</location>"};
		String[] container = new String[4];
		songList.removeAllElements();
		
		System.setSecurityManager(new RMISecurityManager());
		try
		{
			//String url = "//"+my_serverHost+"/SAMPLE-SERVER";
			//RMIServer remoteObject = (RMIServer)Naming.lookup(url);
			//FileWriter fstream = new FileWriter("./tester.xml");
	        //BufferedWriter out = new BufferedWriter(fstream);
	        //out.write(remoteObject.listOfSongs());
	    	//out.close();
			File file = new File("/home/neodymium/workspace/ussProject/src/client/tester.xml");
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			DataInputStream dis = new DataInputStream(bis);
			String line;
			int start, finish;
			while (dis.available() != 0)
			{
				line = dis.readLine();
				for(int i=0,j=0;i<tags.length;i+=2,j++){
					start = line.indexOf((String)tags[i])+tags[i].length();
					finish = line.indexOf(tags[i+1]);
					container[j]=line.substring(start, finish);
					System.out.println(container[j]);
				}
				songList.addElement(container);
			}	
			fis.close();
			bis.close();
			dis.close();
			
		}
		catch (RemoteException exc)
		{
		  	System.out.println("Error in lookup: " + exc.toString());
		}
		catch (java.net.MalformedURLException exc)
		{
		  	System.out.println("Malformed URL: " + exc.toString());
		}/*
		catch (java.rmi.NotBoundException exc)
		{
		  	System.out.println("NotBound: " + exc.toString());
		}*/
		catch (FileNotFoundException e) 
		{
			System.out.println("File not found: "+e.toString());
		}
		catch (IOException e) 
		{
		    System.out.println("IOException: "+e.toString());
		}
	}
	
	//TODO: Select Song
	
	public void selectSong(String[] song)
	{
		try
		{
			String url = "//"+my_serverHost+"/SAMPLE-SERVER";
			RMIServer remoteObject = (RMIServer)Naming.lookup(url);
			//remoteObject.addSongToPlaylist(song);
			
		}
		catch (RemoteException exc)
		{
		  	System.out.println("Error in lookup: " + exc.toString());
		}
		catch (java.net.MalformedURLException exc)
		{
		  	System.out.println("Malformed URL: " + exc.toString());
		}
		catch (java.rmi.NotBoundException exc)
		{
		  	System.out.println("NotBound: " + exc.toString());
		}
	}
	
	 // TODO: Show servers available.
	/*
	public Vector getServers()
	{

	}
	*/
	 // TODO: Connect to a server.
	
	public void connectToServer(String serverName)
	{
		
		
	}
	
	 // TODO: Disconnect from a server.
	
	public void disconnectFromServer()
	{
		
	}
	
	// TODO: Show services available.
	
	public void showServices()
	{
		
	}
	
	// TODO: Show handshaking.
	
	public String showHandshaking()
	{
		return "";
	}
	
	public boolean isConnected()
	{
		return true;
	}

   	public void sendMessage(String a_message)
	{
      		try
		{
		 	Socket toServer = new Socket(my_serverHost, my_serverPort);
			PrintWriter out = new PrintWriter(toServer.getOutputStream(), true);
		 	out.println(a_message);
			BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
			String msg = in.readLine();
			System.out.println("Received message: " + msg);
		 	out.close();
		 	toServer.close();
      		}
		catch (IOException ioe)
		{
        	 	ioe.printStackTrace();
      		}
		catch (SecurityException se)
		{
         		se.printStackTrace();
      		}
   	}

	static class SampleListener implements ServiceListener
	{
      		public void serviceAdded(final ServiceEvent event)
		{
         		System.out.println("Service added   : " + event.getName() + "." + event.getType());
			event.getDNS().requestServiceInfo(event.getType(), event.getName(), 0);
      		}

      		public void serviceRemoved(ServiceEvent event)
		{
         		System.out.println("Service removed : " + event.getName() + "." + event.getType());
      		}

      		public void serviceResolved(ServiceEvent event)
      		{
				int port = 0;
			 	try
				{
			    		port = event.getInfo().getPort();
			 	}
				catch (NumberFormatException nfe)
				{
				    	System.err.println("The value provided for the port is not an integer");
				    	nfe.printStackTrace();
			 	}
				String host = event.getInfo().getHostAddress();
				//String message = "A test Message of some sort.";
	         		System.out.println("Service resolved: " + event.getInfo().getName() + ", host: " + host + ", port: " + port);
			 	//Client client = new Client();
			 	//client.sendMessage("One");
			 	/*
				System.setSecurityManager(new RMISecurityManager());
				try
				{
				  	System.out.println("Security Manager loaded");
				  	String url = "//"+host+"/SAMPLE-SERVER";
				  	RMIServer remoteObject = (RMIServer)Naming.lookup(url);
				 	System.out.println("Got remote object");
				  	//System.out.print
					System.out.println(remoteObject.listOfSongs());
				}
				catch (RemoteException exc)
				{
				  	System.out.println("Error in lookup: " + exc.toString());
				}
				catch (java.net.MalformedURLException exc)
				{
				  	System.out.println("Malformed URL: " + exc.toString());
				}
				catch (java.rmi.NotBoundException exc)
				{
				  	System.out.println("NotBound: " + exc.toString());
				}
				*/
      		}
   	}

   
   	public static void main(String[] args) throws IOException
	{
		
		final JmDNS jmdns = JmDNS.create();
		jmdns.addServiceListener(SERVICE_TYPE, new SampleListener());
      	//Client c = new Client();
      	//c.getListOfSongs();
   	}
}